import java.io.File;
import java.sql.SQLException;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JOptionPane;

/* 
 * 	Notifications.java - A class that warns the employee when he/she recieves an e-mail.
 * 
 * 	@Author : BilCIS
 */


public class Notification 
{
	// properties
	private	Mail m;
	
	private int numOfMail;	
	
	private	Mysql mysql;
	
	static boolean keepRunning;
	
	
	// constructor
	public Notification(int ID) throws SQLException
	{
		keepRunning = true;
		mysql = new Mysql(ID);
		m = new Mail(mysql.getGmailUsername(), mysql.getGmailPassword());
		numOfMail = m.getUnreadMessage();
		start();
	}
	
	// stars checking with every after 10 seconds
	public void start()
	{
		int delay = 1000; // delay for 1 sec. 
		int period = 10000; // repeat every 10 sec. 
		Timer timer = new Timer(); 
		timer.scheduleAtFixedRate(new TimerTask() 
		{ 
		        public void run() 
		        { 	
		        	if ( keepRunning )
		        	{
			        	try 
			        	{
							m = new Mail(mysql.getGmailUsername(), mysql.getGmailPassword());
						} catch (SQLException e1) {
							e1.printStackTrace();
						}
			        	int currentNumOfMail = m.getUnreadMessage();
			     		if ( numOfMail < currentNumOfMail )
			     		{ // checks num of mail
							try 
			     			{
								new PopUpGUI( m.getMail(currentNumOfMail - 1), "New Message!");

								Music receivedmail = new Music( new File("receivedmail.wav").getAbsolutePath() );
								receivedmail.play();
								
								numOfMail = currentNumOfMail;
							} catch (Exception e) 
							{
								JOptionPane.showMessageDialog(null, e.getMessage() );
								e.printStackTrace();
							}
			     		}
		        	}
		        } 
		 }, delay, period);	
	}
}
